import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
import { defineStore } from 'pinia';

// 创建自定义持久化存储
const piniaPersistConfig = (id) => {
  return {
    key: `${id}`,
    storage: {
      getItem(key) {
        return uni.getStorageSync(key);
      },
      setItem(key, value) {
        uni.setStorageSync(key, value);
      },
    },
  };
};

// 用户状态
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: uni.getStorageSync('userInfo') || {},
    token: uni.getStorageSync('token') || '',
    refreshToken: uni.getStorageSync('refreshToken') || '',
    addressList: uni.getStorageSync('addressList') || [],
    searchHistory: uni.getStorageSync('searchHistory') || [],
  }),
  actions: {
    updateUserInfo(userInfo) {
      this.userInfo = userInfo;
      uni.setStorageSync('userInfo', userInfo);
    },
    // 更新token
    updateToken(token, refreshToken) {
      this.token = token;
      this.refreshToken = refreshToken;
      uni.setStorageSync('token', token);
      uni.setStorageSync('refreshToken', refreshToken);
    },
    clearUserData() {
      this.userInfo = {};
      this.token = '';
      this.refreshToken = '';
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('token');
      uni.removeStorageSync('refreshToken');
    },
    // 清除地址
    clearAddress() {
      this.addressList = [];
      uni.removeStorageSync('addressList');
    },
  },
  persist: piniaPersistConfig('user'),
});

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export default pinia;
